package com.das.qiniufilestatechange.service;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.storage.model.StorageType;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liyh <levart@163.com>
 * @version 20250114
 */
@Service
public class QiniuFileManage {

    public static final Logger log = LoggerFactory.getLogger(QiniuFileManage.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // marker
    public static final String REDIS_MARKER_KEY = "qiniu.change.type.marker";
    public static final String REDIS_ALL_COUNT = "qiniu.change.type.all.count";
    public static final String REDIS_CHANGE_COUNT = "qiniu.change.type.change.count";

    public void updateFileType(){
        log.info("start");

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        //...其他参数参考类注释

        String accessKey = "H4h2uEFDh3NDASUbn7gYU5p4Vmy5KIdJF7rcnL-4";
        String secretKey = "HVIcaz0X7UrIFpVKI3EIrdNrX0PWC7f8nStu7bEA";
        String bucket = "cn-service-pic";

        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        String marker = "";
        FileInfo[] items = null;
        Long currentUpdate = 0L;

        do{
            try {

                // 获取上次结束位置
                String lastMarker = stringRedisTemplate.opsForValue().get(REDIS_MARKER_KEY);
                FileListing fileListing = bucketManager.listFiles(bucket, prefix, lastMarker, limit, delimiter);
                marker = fileListing.marker;
                log.info("fileListing.marker:{}",fileListing.marker);
                // 存储到redis中
                stringRedisTemplate.opsForValue().set(REDIS_MARKER_KEY,fileListing.marker);


                items = fileListing.items;
                for (FileInfo item : items) {
                    Long increment1 = stringRedisTemplate.opsForValue().increment(REDIS_ALL_COUNT, 1);

                    // 计算文件存储天数
                    String putTimeStr = String.valueOf(item.putTime);
                    String str = putTimeStr.substring(0, putTimeStr.length() - 7);
                    long qiniuTime = Long.parseLong(str) * 1000;
                    long time = new Date().getTime();
                    long day = (time - qiniuTime)/86400000;

                    if(day > 180 && item.type == 0){
                        currentUpdate ++;
                        Long increment2 = stringRedisTemplate.opsForValue().increment(REDIS_CHANGE_COUNT, 1);
                        log.info("{},{}-{}--{}",item.key,increment1,increment2,currentUpdate);
                        // 更改为低频存储
                        //修改文件类型
                        try {
                            bucketManager.changeType(bucket,item.key, StorageType.INFREQUENCY);
                        } catch (QiniuException ex) {
                            log.error(ex.getMessage(),ex);
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }

        }while (!"".equals(marker) && items != null && items.length > 0 && currentUpdate < 10000000);

        log.info("finish,currentUpdate:{}",currentUpdate);
    }


}
